package com.zebra.gateway;

import com.zebra.common.concurrent.ZebraExecutorManager;
import com.zebra.common.concurrent.ZebraScheduler;
import com.zebra.gateway.protocol.GatewaySendMessageUtil;
import com.zebra.gateway.session.SessionManager;
import com.zebra.remoting.config.BasisCommandCode;
import com.zebra.remoting.config.ONNUMTORAmessage;
import com.zebra.remoting.config.ServerType;
import com.zebra.remoting.connection.Connection;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @Auther: SK
 * @Date: 2021/8/21 22:23
 * @Description:
 */
public class OnlineNumberService {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance(OnlineNumberService.class);
    private long onlineNumber;

    public void start(){
        ZebraScheduler scheduler = new ZebraScheduler(1);
        scheduler.scheduleWithFixedDelay(this::sendOnlineNumber, 200,  30000, TimeUnit.MILLISECONDS, ZebraExecutorManager.getInstance().getDefaultExecutor());
    }

    private void sendOnlineNumber(){
        long newOnlineNumber = SessionManager.getInstance().getOnlineNumber();
        if (newOnlineNumber != onlineNumber){
            onlineNumber = newOnlineNumber;
            Connection registerConn = GwConfigInfoManager.getInstance().getRAConnection();
            if (null == registerConn){
                logger.error("Send onlineNumber to register is null; gw {}", GwConfigInfoManager.getInstance().getGwServerInfo().toString());//如果没有注册中心
                return;
            }
            ONNUMTORAmessage message = new ONNUMTORAmessage();
            message.setServerId(GwConfigInfoManager.getInstance().getGwServerInfo().getServerId());
            message.setServerType(ServerType.Gateway.value());
            message.setOnlineNumber(onlineNumber);
            if (logger.isInfoEnabled()){
                logger.info("Send Send onlineNumber to register {}", message);
            }
            GatewaySendMessageUtil.sendMessage(registerConn.getChannel(), BasisCommandCode.ONNUMTORA.cmd(), message);
        }
    }

}
